#include "questionlistwidget.h"
#include "ui_questionlistwidget.h"
#include "questioncard.h"
#include "debug.h"

QuestionListWidget::QuestionListWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::QuestionListWidget)
{
    ui->setupUi(this);
    init();
}

QuestionListWidget::~QuestionListWidget()
{
    delete ui;
}

void QuestionListWidget::clear()
{
    setCardList(QList<model::QuestionClusterInfo>());
}

#include <QScrollBar>
void QuestionListWidget::setCardList(const QList<model::QuestionClusterInfo> &questions)
{
    if(!_scrollArea || !_container || !_container->layout()) return;
    this->hide();

    qint64 cardsSize = _cards.size(), size = questions.size();
    qDebug() << "已有" << cardsSize << "个卡片, 设置" << size << "个卡片";

    if (cardsSize < size) {
        for(int i = 0, need = size - cardsSize; i < need; ++i) {
            auto card = new QuestionCard(_container);
            _cards.push_back(card);
            _container->layout()->addWidget(card);
        }
    } else if (cardsSize > size) {
        for (int i = size; i < cardsSize; ++i) {
            _container->layout()->removeWidget(_cards[i]);
            _cards[i]->deleteLater();
        }
        _cards.resize(size);
    }

    for(int i = 0; i < size; ++i) {
        auto& questionCluster = questions[i];
        if (questionCluster.questions.isEmpty()) {
            continue;
        }
        _cards[i]->set(questionCluster);
        QObject::disconnect(_cards[i], &QuestionCard::clicked, nullptr, nullptr);
        connect(_cards[i], &QuestionCard::clicked, [this, questionCluster]{
            this->showQuestion(questionCluster);
        });
    }

    _scrollArea->verticalScrollBar()->setValue(0);
    this->show();
}

void QuestionListWidget::init()
{
    initPanel();
    initBody();
    initStyleSheet();
}

void QuestionListWidget::initStyleSheet()
{
    ui->panel->setStyleSheet(R"(background-color: transparent;)");
    ui->head->setStyleSheet(R"(background-color: transparent;)");
    ui->body->setStyleSheet(R"(background-color: transparent;)");

    ui->lineEdit_search->setStyleSheet(R"(QLineEdit { padding-left: 30px; border-radius: 15px; border: 1px solid transparent; background: qlineargradient( x1:0, y1:0, x2:1, y2:0, stop:0 #dbeafe, stop:1 #fce7f3 ); color: #4b5563; font-size: 22px; background-repeat: no-repeat; background-position: 10px center; background-origin: content; background-clip: padding; } QLineEdit:!focus { color: #9ca3af; })");
    ui->btn_time_window->setStyleSheet(R"(QPushButton { background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #f8f1f8, stop:1 #fbe6ee); border: none; color: #787F8D; border-radius: 12px; padding: 12px; } QPushButton:hover { background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #fcdfea, stop:1 #f8c7e1); })");
    ui->btn_fliter->setStyleSheet(R"( QPushButton { background-repeat: no-repeat; background-position: center; background-image: url(:/ui/btn_close_50.png); border: none; background-color: transparent; } QPushButton:hover, QPushButton:pressed { background-image: url(:/ui/btn_close_100.png); })");
}

void QuestionListWidget::initPanel()
{
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    this->layout()->setContentsMargins(0, 0, 0, 0);
    this->layout()->setSpacing(0);

    ui->layout_panel->setContentsMargins(0, 0, 0, 0);
    ui->layout_panel->setSpacing(0);

    ui->head->setFixedHeight(60);
    ui->head->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    ui->layout_head->setContentsMargins(0, 5, 10, 5);
    ui->layout_head->setSpacing(10);

    ui->lineEdit_search->setFixedSize(350, 50);

    ui->body->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}

#include <QScrollArea>
void QuestionListWidget::initBody()
{
    // 1) 新建一个主布局，设置给 ui->body
    QVBoxLayout *mainLayout = new QVBoxLayout(ui->body);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 2) 新建 QScrollArea 及其内部容器
    _scrollArea = new QScrollArea(ui->body);

    _container = new QWidget;
    _container->setStyleSheet(R"( background-color: transparent;)");

    QVBoxLayout* containerLayout = new QVBoxLayout(_container);
    containerLayout->setSpacing(10);
    containerLayout->setContentsMargins(20, 0, 20, 0);
    containerLayout->setAlignment(Qt::AlignTop); // 布局内所有子控件顶对齐

    // 3) 设置 scrollArea
    _scrollArea->setWidget(_container);
    _scrollArea->setWidgetResizable(true);
    _scrollArea->setStyleSheet(R"( QScrollArea { border: none; background-color: transparent; } QScrollArea > QWidget { background-color: transparent; } QScrollBar:vertical { background-color: transparent; /* 透明背景 */ width: 9px; border: none; } QScrollBar::handle:vertical { background-color: #dcdfe4; border-radius: 4px; min-height: 20px; /* 最小高度 */ } QScrollBar::handle:vertical:hover { background-color: #bec3ca; } QScrollBar::handle:vertical:pressed { background-color: #a8adb5; /* 新增:按下状态 */ } /* 关键:定义滑块上下的空白区域 */ QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background: transparent; } QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0px; /* 隐藏箭头 */ background: transparent; } QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { background: none; } )");
    _scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);

    // 4) 将 scrollArea 加到主布局里
    mainLayout->addWidget(_scrollArea);
}

#include "questiondialog.h"
void QuestionListWidget::showQuestion(const model::QuestionClusterInfo &question)
{
    QuestionDialog dialog(this);
    dialog.set(question);
    dialog.exec();
}

#include "model/datacenter.h"
void QuestionListWidget::on_btn_fliter_clicked()
{
#if TEST_UI
    model::QuestionClusterInfo info;
    model::QuestionInfo question;
    question.content = "这是一个问题";
    for(int i = 0; i < 4; ++i) question.content += question.content;
    question.tags.append(QList<QString>({"标签1", "标签222222222222222222", "标签3", "标签4"}));
    info.questions.append(question);
    info.standardAnswer = "这是一个问题的答案";
    for(int i = 0; i < 4; ++i) info.standardAnswer += info.standardAnswer;
    info.cnt = 1;
    QList<model::QuestionClusterInfo> list;
    for(int i = 0; i < rand() % 100; ++i) {
        info.tags = question.tags;
        info.tags.resize(i % 4 + 1);
        for(int j = 0; j < i; ++j) {
            info.questions.append(question);
        }
        list.append(info);
    }
    setCardList(list);
#endif
    model::SearchLimits limits;
    limits.searchKey = "推荐";
    auto& dataCenter = model::DataCenter::getInstance();
    dataCenter.searchQuestionClusterAsync(limits);
    connect(&dataCenter, &model::DataCenter::searchQuestionClusterDone, this, &QuestionListWidget::searchQuestionClusterDone, Qt::ConnectionType::UniqueConnection);
}

void QuestionListWidget::searchQuestionClusterDone()
{
    auto ret = model::DataCenter::getInstance().getSearchQuestionClusterResult();
    if (ret)
        setCardList(*ret);
}

